using System;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace InnerFireEditor {
  public class FileManager {
    // 静态扩展名列表
    private static readonly List<string> SupportedExtensions = new List<string> { ".txt", ".xml" };


    public FileManagerItem RootItem { get; private set; }

    public void Read(string path) {
      if (string.IsNullOrWhiteSpace(path))
        throw new ArgumentException("路径不能为空");

      if (!Directory.Exists(path))
        throw new DirectoryNotFoundException($"路径不存在: {path}");

      RootItem = ReadDirectory(path);
    }

    /// <summary>
    /// 检查文件扩展名是否在支持列表中
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <returns>如果是支持的扩展名返回true，否则false</returns>
    public static bool IsFileType(string filePath) {
      if (string.IsNullOrWhiteSpace(filePath))
        return false;

      string extension = Path.GetExtension(filePath)?.ToLowerInvariant();
      return SupportedExtensions.Contains(extension);
    }

    private FileManagerItem ReadDirectory(string directoryPath) {
      var directoryInfo = new DirectoryInfo(directoryPath);
      var currentItem = new FileManagerItem(directoryInfo.Name, directoryPath, true);

      try {
        foreach (var subDir in directoryInfo.GetDirectories()) {
          currentItem.Children.Add(ReadDirectory(subDir.FullName));
        }

        foreach (var file in directoryInfo.GetFiles()) {
          if (IsFileType(file.FullName)) {
            currentItem.Children.Add(new FileManagerItem(file.Name, file.FullName, false));
          }

        }
      } catch (UnauthorizedAccessException) {
        currentItem.Name += " (无访问权限)";
      } catch (Exception ex) {
        currentItem.Name += $" (读取错误: {ex.Message})";
      }

      return currentItem;
    }

    /// <summary>
    /// 将文件结构填充到TreeView控件
    /// </summary>
    /// <param name="treeView">目标TreeView控件</param>
    /// <param name="withIcons">是否显示图标</param>
    public void Fill(TreeView treeView, bool withIcons = true) {
      if (RootItem == null)
        throw new InvalidOperationException("请先调用Read方法读取文件结构");

      treeView.Items.Clear();
      var rootNode = CreateTreeNode(RootItem, withIcons);
      treeView.Items.Add(rootNode);
    }

    private TreeViewItem CreateTreeNode(FileManagerItem item, bool withIcons) {
      var node = new TreeViewItem {
        Header = CreateHeader(item, withIcons),
        Tag = item, // 存储对象
        IsExpanded = true
      };

      foreach (var child in item.Children) {
        node.Items.Add(CreateTreeNode(child, withIcons));
      }

      return node;
    }



    private StackPanel CreateHeader(FileManagerItem item, bool withIcons) {
      var stackPanel = new StackPanel { Orientation = Orientation.Horizontal };

      if (withIcons) {
        var iconControl = item.IsDirectory ?
            IconManager.GetFolderIconControl() :
            IconManager.GetFileIconControl(item.FullPath);

        if (iconControl != null) {
          stackPanel.Children.Add(iconControl);
        }
      }

      stackPanel.Children.Add(new TextBlock { Text = item.Name });
      return stackPanel;
    }

    public static void ConvertXmlToGif(string path) {
      if (!Directory.Exists(path)) {
        MessageBox.Show($"目录不存在: {path}", "通知");
        return;
      }

      // 获取所有.xml文件（包括子目录）
      var xmlFiles = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories);

      foreach (var xmlFile in xmlFiles) {
        try {
          string gifFile = Path.ChangeExtension(xmlFile, ".gif");

          // 复制文件并覆盖已存在的文件
          File.Copy(xmlFile, gifFile, overwrite: true);          
        } catch (Exception ex) {
          MessageBox.Show($"处理文件 {xmlFile} 时出错: {ex.Message}", "通知");
        }
      }

      MessageBox.Show($"已转换：{xmlFiles.Length}", "通知");
    }


  }
}